package com.newblog.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.newblog.common.AppVarible;
import com.newblog.common.ResultAjax;
import com.newblog.common.SessionUtils;
import com.newblog.mapper.UserMapper;
import com.newblog.model.userinfo;
import com.newblog.model.vo.UserInfoVo;
import com.newblog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with Intellij IDEA.
 * Description;
 * UserInfo:TQ02
 * Data:2023-12-10
 * Time:12:33
 * Text：
 */
@RestController
@RequestMapping("/user")
public class Usercontroller {
    @Autowired
    UserService userService;
    @Autowired
    UserMapper mapper;


    @RequestMapping("/insertAll")
    public void insertAll(@RequestBody List<userinfo> user){

    }
//注册
    @PostMapping("/reg")
    public ResultAjax insert(userinfo user){
        userinfo u1=mapper.selectOne(new QueryWrapper<userinfo>().eq("username",user.getUsername()));

        if(user==null || !StringUtils.hasLength(user.getUsername())
            || !StringUtils.hasLength(user.getPassword()) || u1!=null)
            return ResultAjax.fail(1,"非法");
       if(userService.save(user)){
           return ResultAjax.succ("注册成功");
       }
        return ResultAjax.fail(1,"非法");
    }
//登陆
    @RequestMapping("/login")
    public ResultAjax login(UserInfoVo user, HttpServletRequest req){
        if(user==null || !StringUtils.hasLength(user.getUsername())
            || !StringUtils.hasLength(user.getPassword()))
            return ResultAjax.fail(-1,"非法");

        userinfo u1=mapper.selectOne(new QueryWrapper<userinfo>().eq("username",user.getUsername()));
        if(u1==null || u1.getUserid()==0 || !user.getPassword().equals(u1.getPassword())){
            return ResultAjax.fail(2,"账号或密码错误");
        }
            HttpSession session=req.getSession();
            session.setAttribute(AppVarible.SESSION_USERINFO_KEY,u1);
            return ResultAjax.fail(200,"登陆成功");
    }
//注销
    @RequestMapping("/logout")
    public ResultAjax logout(HttpServletRequest req){
        HttpSession session=req.getSession(false);
        if(session!=null && session.getAttribute(AppVarible.SESSION_USERINFO_KEY)!=null){
            session.removeAttribute(AppVarible.SESSION_USERINFO_KEY);
        }
        return ResultAjax.succ(1);
    }

//查询当前用户
    @RequestMapping("/check")
    public ResultAjax check(HttpServletRequest req){
        userinfo user= SessionUtils.getUser(req);
        if(user==null){
            return ResultAjax.fail(-1,"请登陆");
        }else{
            return ResultAjax.succ(user);
        }
    }


}
